<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of NewApartamentListValidator
 *
 * @author verminu
 */
class NewApartamentListPostValidator extends sfValidatorSchema
{
  const DUPLICATE_AP = 'duplicate_ap';

  protected function configure($options = array(), $messages = array())
  {
    parent::configure($options, $messages);

    $this->addMessage(self::DUPLICATE_AP, 'Acest număr apare de mai multe ori în formular.');
  }

  protected function doClean($values)
  {
    $errorSchema = new sfValidatorErrorSchema($this);
    $errorList = new sfValidatorErrorSchema($this);

    // se verifica daca numerele apartamentelor sunt diferite intre ele
    $keys = array_reverse(array_keys($values[NewApartamentListForm::WRAPPER_NAME]));
    for ($index = 0; $index < count($keys); $index++)
    {
      $number = $values[NewApartamentListForm::WRAPPER_NAME][$keys[$index]]['number'];

      for ($i = $index + 1; $i < count($keys); $i++)
      {
        if ($number == $values[NewApartamentListForm::WRAPPER_NAME][$keys[$i]]['number'])
        {
          // creez eroarea si o asociez field-ului corespunzator
          $error = new sfValidatorError($this, self::DUPLICATE_AP);

          $errorApartament = new sfValidatorErrorSchema($this);
          $errorApartament->addError($error, 'number');

          $errorList->addError($errorApartament, (string)$keys[$index]);

          break;
        }
      }
    }

    if (count($errorList))
    {
      $errorSchema->addError($errorList, NewApartamentListForm::WRAPPER_NAME);

      throw $errorSchema;
    }

    return $values;
  }
}
